<template>
  <div class="btnWrap" style="background-color: #ffffff">
    <el-button
      type="primary"
      @click="saveForm"
      :loading="loading"
      v-hasPermi="['order:transfer-item-management:save']"
      v-if="!isDis()"
    >
      保存
    </el-button>
    <el-button
      type="primary"
      @click="submitForm"
      :loading="loading"
      v-hasPermi="['order:transfer-item-management:submit']"
      v-if="!isDis()"
    >
      提交
    </el-button>
    <el-button @click="goBack"> 返回 </el-button>
  </div>
  <div class="contentView" :style="`height: ${contentHeight}px`">
    <!-- 转项部件 -->
    <ContentWrap>
      <div class="contentTop">
        <div>
          <span class="title">转项部件</span>
        </div>
        <div>
          <el-button @click="openPartDialog" type="primary" :disabled="isDis()"
            >选择转项部件</el-button
          >
        </div>
      </div>
      <el-table
        ref="multipleTableRef"
        border
        row-key="id"
        :height="tableHeight"
        :tree-props="{ children: 'children' }"
        v-loading="loading"
        :data="partList"
        default-expand-all
        @row-click="rowClick"
        :row-style="tableCellStyle"
        class="tableView"
        highlight-current-row
      >
        <el-table-column
          :label="item.label"
          :align="item.align"
          :min-width="item.width"
          :prop="item.val"
          v-for="item in transferListTitle"
          :key="item.val"
        >
          <template #default="scope">
            <template v-if="item.dictType">{{
              getDictLabel(item.dictType, scope.row[item.val])
            }}</template>
            <template v-else>
              <!-- 转项数量 -->
              <el-input
                v-nextInput="'taskTransferItemNumber'"
                name="taskTransferItemNumber"
                v-if="item.val == 'taskTransferItemNumber'"
                v-model="scope.row[item.val]"
                type="number"
                min="0"
                :disabled="isDis()"
              />
              <temmplate v-else>
                <el-button
                  v-if="item.label == '图纸图号'"
                  type="primary"
                  link
                  @click="jumpPdfFile(scope.row[item.val],scope.row.productNumber)"
                  >{{ scope.row[item.val] }}
                </el-button>
                <template v-else>{{ scope.row[item.val] }}</template>
              </temmplate>
            </template>
          </template>
        </el-table-column>
      </el-table>
    </ContentWrap>
    <!-- 异常物料 -->
    <contentWrap>
      <div class="contentTop">
        <div>
          <span class="title">异常物料</span>
        </div>
        <div>
          <el-button @click="openAbnormalDialog" type="primary" :disabled="isDis()"
            >选择异常物料</el-button
          >
        </div>
      </div>
      <el-table
        ref="abnormalTableRef"
        border
        row-key="id"
        :height="tableHeight"
        v-loading="loading"
        :data="[dataList.data.abnormalList]"
        class="tableView"
      >
        <el-table-column
          :label="item.label"
          :align="item.align"
          :min-width="item.width"
          :prop="item.val"
          v-for="item in abnormalTitle"
          :key="item.val"
        >
          <template #default="scope">
            <template v-if="item.dictType">{{
              getDictLabel(item.dictType, scope.row[item.val])
            }}</template>
            <template v-else>
              <!-- 转项数量 -->
              <el-input
                v-nextInput="'abnormalTransferItemNumber'"
                name="abnormalTransferItemNumber"
                v-if="item.val == 'abnormalTransferItemNumber'"
                v-model="scope.row[item.val]"
                type="number"
                min="0"
                :disabled="isDis()"
              />
              <!-- 转项成本 -->
              <el-input
                v-nextInput="'abnormalTransferItemCost'"
                name="abnormalTransferItemCost"
                v-else-if="item.val == 'abnormalTransferItemCost'"
                v-model="scope.row[item.val]"
                type="number"
                min="0"
                :disabled="isDis()"
              />
              <temmplate v-else>
                <el-button
                  v-if="item.label == '图纸图号'"
                  type="primary"
                  link
                  @click="jumpPdfFile(scope.row[item.val],scope.row.productNumber)"
                  >{{ scope.row[item.val] }}
                </el-button>
                <template v-else>{{ scope.row[item.val] }}</template>
              </temmplate>
            </template>
          </template>
        </el-table-column>
      </el-table>
    </contentWrap>
  </div>
  <partDialog ref="partDialogRef" @setPartData="setPartData" />
  <abnormalDialog ref="abnormalDialogRef" @setAbnormalData="setAbnormalData" />
</template>
<script setup lang="ts">
import { getDictLabel } from '@/utils/dict'
import * as TransferItemManagementApi from '@/api/orderManagement/transferManagement/transferItemManagement'
import { useTagsViewStore } from '@/store/modules/tagsView'
import partDialog from './partDialog.vue'
import { jumpPdfFile } from '@/utils/formCreate'
import abnormalDialog from './abnormalDialog.vue'
const message = useMessage() // 消息弹窗
const loading = ref(false) //数据加载中
const contentHeight = ref(0)
const partList = ref() // 转项数据
//选中的转项数据
let dataList = reactive({
  data: {
    abnormalList: {}
  }
})
//禁用
const isDis = () => {
  if (formType.value === 'view') {
    return true
  }
  return false
}
// 点击某个单元格
const rowClick = async (row) => {
  dataList.data = row
}
const tableCellStyle = (row) => {
  if (dataList.data.id === row.row.id) {
    return {
      backgroundColor: '#efefef'
    }
  } else {
    return {
      backgroundColor: '#fff'
    }
  }
}
// 打开选择部件弹框
const partDialogRef = ref()
const openPartDialog = () => {
  partDialogRef.value.open(partList.value)
}

// 打开异常物料弹框
const abnormalDialogRef = ref()
const openAbnormalDialog = () => {
  if (dataList.data.hasOwnProperty('id')) {
    abnormalDialogRef.value.open(dataList.data.abnormalList)
  } else {
    message.warning('请先选择转项部件')
  }
}

// 设置转项部件
const setPartData = (data) => {
  let obj = {}
  data = data.reduce((pre, cur) => {
    obj[cur.productNumber] ? '' : (obj[cur.productNumber] = true && pre.push(cur))
    return pre
  }, [])
  partList.value = data
}

// 设置异常物料
const setAbnormalData = (data) => {
  if (data.length) {
    dataList.data.abnormalList = data[0]
  } else {
    dataList.data.abnormalList = {}
  }
}

/**返回 */
const tagsViewStore = useTagsViewStore()
const route = useRouter() // 路由
const goBack = async () => {
  //获取当前路由并删除tagView
  tagsViewStore.delView(route.currentRoute.value)
  //跳转列表页
  route.push({
    path: '/orderManagement/orderManagement/transferManagement/TransferItemManagement'
  })
}
// 保存
const saveForm = async () => {
  loading.value = true
  const data = {
    transferItemNo: transferItemNo.value,
    productionTaskOrderVo: partList.value
  }
  try {
    await TransferItemManagementApi.saveTransferItemManagement(data)
    message.success('操作成功')
    goBack()
  } finally {
    loading.value = false
  }
}
//校验
const roleList = ref([null, undefined, '', 0, '0'])
const checkDataArr = (arr) => {
  arr.map((item) => {
    if (
      roleList.value.includes(item.taskTransferItemNumber) ||
      roleList.value.includes(item.abnormalList.abnormalTransferItemNumber) ||
      roleList.value.includes(item.abnormalList.abnormalTransferItemCost)
    ) {
      message.error('数据不能为空或0')
      flag.value = true
    }
    if (parseFloat(item.taskTransferItemNumber) > parseFloat(item.planQuantity)) {
      message.error('转项数量不能大于计划数量')
      flag.value = true
    }
    if (
      parseFloat(item.abnormalList.abnormalTransferItemNumber) >
      parseFloat(item.abnormalList.completeQuantity)
    ) {
      message.error('转项数量不能大于完工数量')
      flag.value = true
    }
    if (
      parseFloat(item.taskTransferItemNumber) < 0 ||
      parseFloat(item.abnormalList.abnormalTransferItemNumber) < 0
    ) {
      message.error('转项数量不能小于0')
      flag.value = true
    }
    if (
      parseFloat(item.abnormalList.abnormalTransferItemCost) < 0
    ) {
      message.error('转项成本不能小于0')
      flag.value = true
    }
    if (item.children.length) {
      checkDataArr(item.children)
    }
  })
}
/** 提交表单 */
const flag = ref(false)
const submitForm = async () => {
  const data = {
    transferItemNo: transferItemNo.value,
    productionTaskOrderVo: partList.value
  }
  await checkDataArr(data.productionTaskOrderVo)
  if (flag.value) {
    return
  }
  console.log(flag.value)
  loading.value = true
  try {
    await TransferItemManagementApi.submitTransferItemManagement(data)
    message.success('操作成功')
    goBack()
  } finally {
    loading.value = false
  }
}
//转项列表表头
const transferListTitle = ref([
  {
    label: '产品编号',
    val: 'productNumber',
    width: 250,
    align: 'left'
  },
  {
    label: '产品名称',
    val: 'productName',
    width: 200,
    align: 'left'
  },
  {
    label: '产品规格',
    val: 'productStandard',
    width: 200,
    align: 'left'
  },
  {
    label: '编号',
    val: 'serialNumber',
    width: 200,
    align: 'left'
  },
  {
    label: '部件编号',
    val: 'partNumber',
    width: 200,
    align: 'left'
  },
  {
    label: '部件名称',
    val: 'partName',
    width: 200,
    align: 'left'
  },
  {
    label: '图纸图号',
    val: 'partDrawingNumber',
    width: 200,
    align: 'left'
  },
  {
    label: '部件规格',
    val: 'partSpecification',
    width: 200,
    align: 'left'
  },
  {
    label: '材质',
    val: 'material',
    width: 200,
    align: 'left'
  },
  {
    label: '规格',
    val: 'specification',
    width: 200,
    align: 'left'
  },
  {
    label: '净尺寸(长)',
    val: 'netSizeLength',
    width: 200,
    align: 'left'
  },
  {
    label: '净尺寸(宽)',
    val: 'netSizeWidth',
    width: 200,
    align: 'left'
  },
  {
    label: '下料尺寸(长)',
    val: 'cuttingSizeLength',
    width: 200,
    align: 'left'
  },
  {
    label: '下料尺寸(宽)',
    val: 'cuttingSizeWidth',
    width: 200,
    align: 'left'
  },
  {
    label: '计划数量',
    val: 'planQuantity',
    width: 100,
    align: 'left'
  },
  {
    label: '转项数量',
    val: 'taskTransferItemNumber',
    width: 100,
    align: 'left'
  },
  {
    label: '单位',
    val: 'partUnit',
    width: 100,
    align: 'left'
  },
  {
    label: '工序名称',
    val: 'dictProcessName',
    width: 100,
    align: 'left',
    dictType: 'craft_process_name'
  },
  {
    label: '工种',
    val: 'dictTypeOfWork',
    width: 100,
    align: 'left',
    dictType: 'config_manufacturing_details_cutting_process'
  }
])
//异常物料表头
const abnormalTitle = ref([
  {
    label: '产品编号',
    val: 'productNumber',
    width: 250,
    align: 'left'
  },
  {
    label: '产品名称',
    val: 'productName',
    width: 200,
    align: 'left'
  },
  {
    label: '产品规格',
    val: 'productStandard',
    width: 200,
    align: 'left'
  },
  {
    label: '编号',
    val: 'serialNumber',
    width: 200,
    align: 'left'
  },
  {
    label: '部件编号',
    val: 'partNumber',
    width: 200,
    align: 'left'
  },
  {
    label: '部件名称',
    val: 'partName',
    width: 200,
    align: 'left'
  },
  {
    label: '图纸图号',
    val: 'partDrawingNumber',
    width: 200,
    align: 'left'
  },
  {
    label: '部件规格',
    val: 'partSpecification',
    width: 200,
    align: 'left'
  },
  {
    label: '材质',
    val: 'material',
    width: 200,
    align: 'left'
  },
  {
    label: '规格',
    val: 'specification',
    width: 200,
    align: 'left'
  },
  {
    label: '净尺寸(长)',
    val: 'netSizeLength',
    width: 200,
    align: 'left'
  },
  {
    label: '净尺寸(宽)',
    val: 'netSizeWidth',
    width: 200,
    align: 'left'
  },
  {
    label: '下料尺寸(长)',
    val: 'cuttingSizeLength',
    width: 200,
    align: 'left'
  },
  {
    label: '下料尺寸(宽)',
    val: 'cuttingSizeWidth',
    width: 200,
    align: 'left'
  },
  {
    label: '完工数量',
    val: 'completeQuantity',
    width: 100,
    align: 'left'
  },
  {
    label: '转项数量',
    val: 'abnormalTransferItemNumber',
    width: 100,
    align: 'left'
  },
  {
    label: '转项成本（%）',
    val: 'abnormalTransferItemCost',
    width: 150,
    align: 'left'
  },
  {
    label: '单位',
    val: 'partUnit',
    width: 100,
    align: 'left'
  },
  {
    label: '工序名称',
    val: 'dictProcessName',
    width: 100,
    align: 'left',
    dictType: 'craft_process_name'
  },
  {
    label: '工种',
    val: 'dictTypeOfWork',
    width: 100,
    align: 'left',
    dictType: 'config_manufacturing_details_cutting_process'
  }
])
const { query } = useRoute() // 路由的查询
const transferItemNo = ref('')
const formType = ref('')
/** 初始化 **/
onMounted(async () => {
  contentHeight.value = document.body.clientHeight - 132 - 52
  formType.value = query.type
  if (query.transferItemNo) {
    transferItemNo.value = query.transferItemNo
    const transferPart = await TransferItemManagementApi.getTaskByProductNumber(
      transferItemNo.value
    )
    partList.value = transferPart
  }
})
</script>
<style lang="scss" scoped>
:deep(.el-table__body tr.current-row > td) {
  background: #efefef !important;
}
.tableView {
  :deep(.el-input__wrapper) {
    box-shadow: 0 0 0 0px var(--el-input-border-color, var(--el-border-color)) inset;
    cursor: default;
    .el-input__inner {
      cursor: default !important;
      text-align: center;
    }
  }
}
.contentView {
  overflow-y: auto;
}

.btnWrap {
  padding: 10px;
}

.title {
  font-size: 16px;
  font-weight: bold;
  margin: 20px 0;
}
.contentTop {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}
</style>
